<template>
  <el-dialog v-model="modelVisible" width="800" align-center center>
    <template #header>
      <title-view title="批量定价" />
    </template>
    <el-tabs v-model="active" class="tabs-container" @tab-change="change">
      <el-tab-pane label="导入文件表" :name="1"></el-tab-pane>
      <el-tab-pane label="上传记录" :name="2"></el-tab-pane>
    </el-tabs>
    <div class="hint" v-if="active !== 2 && isShowInducts">
      <div>
        <el-icon>
          <WarningFilled />
        </el-icon>
        如果数据处理出现任何错误，根据系统提示进行修改您的库存文件，然后重新上传。
      </div>
      <span @click="isShowInducts = false">不再提示</span>
    </div>
    <div class="hint" v-if="active === 2 && isShowDownTemp">
      <div>
        <el-icon>
          <WarningFilled />
        </el-icon>
        如果数据处理出现任何错误，根据系统提示进行修改您的库存文件，然后重新上传。
      </div>
      <span @click="isShowDownTemp = false">不再提示</span>
    </div>
    <div v-if="active === 1">
      <el-upload v-if="!uploading" class="upload-demo" drag :http-request="customRequest" multiple :show-file-list="false">
        <img src="@/assets/images/image/upload.png" alt="" />
        <div class="el-upload__text">
          <em>上传文件</em>
          <div class="tip">也可以拖拽到此处上传（支持格式：xlsx）</div>
        </div>
        <template #tip>
          <div class="el-upload__tip" @click="handelExport">
            <el-icon>
              <Paperclip />
            </el-icon>
            下载商品SKU数据
          </div>
        </template>
      </el-upload>
      <div v-else class="uploading" :style="{ '--color': status === 'success' ? '#2BA471' : '#D54941' }">
        <el-progress v-if="status === 'loading'" type="circle" :percentage="percentage" />
        <div v-else-if="status === 'success'">
          <el-icon>
            <CircleCheck />
          </el-icon>
        </div>
        <div v-else-if="status === 'error'">
          <el-icon>
            <CircleClose />
          </el-icon>
        </div>
        <div class="status">{{ statusList[status].title }}</div>
        <div class="tip">{{ statusList[status].tip }}</div>
        <div class="dialog-footer">
          <el-button type="primary" @click="next">
            {{ statusList[status].btnText }}
          </el-button>
        </div>
        <div class="success-tip" v-if="status === 'error'" v-html="errorMsg"></div>
      </div>
    </div>
    <div v-if="active === 2" class="table">
      <div class="row">
        <div>上传日期</div>
        <div>文件名称</div>
        <div>上传状态</div>
        <div>操作</div>
      </div>
      <el-scrollbar max-height="300px" ref="scrollRef" @scroll="scroll">
        <el-empty :image-size="100" v-if="!tableList.length" />
        <div class="row" v-for="item in tableList" :key="item.createId">
          <div>{{ item.createTime }}</div>
          <div>{{ item.fileName }}</div>
          <div>{{ item.leadStatus === 1 ? "完成" : "失败" }}</div>
          <div class="operate">
            <img src="@/assets/images/image/down.png" alt="" @click="downFile(item.fileUrl, item.fileName)" />
            <img src="@/assets/images/image/del1.png" alt="" @click="openDel(item.id)" />
          </div>
        </div>
      </el-scrollbar>
    </div>
  </el-dialog>
  <!-- 操作提示 -->
  <el-dialog v-model="visibleDel" width="400" align-center center :show-close="false">
    <div class="sure">
      <div>
        <el-icon>
          <Warning />
        </el-icon>
      </div>
      <span>删除记录后，将无法再次找回此文件，你还要继续吗？</span>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visibleDel = false">取消</el-button>
        <el-button type="primary" @click="handleDel"> 确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { computed, ref } from "vue";
import { ElMessage } from "element-plus";
import { useLocalStorage } from "@vueuse/core";
import upload from "@/utils/upload";
import { CircleCheck, CircleClose, Paperclip, Warning, WarningFilled } from "@element-plus/icons-vue";
import { deleteLogs, logsList, managementImport } from "@/apis/biddingManagement";

const scrollRef = ref(null);
const active = ref(1);
const isShowInducts = useLocalStorage("isShowInducts", true);
const isShowDownTemp = useLocalStorage("isShowDownTemp", true);
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});
const emit = defineEmits(["update:visible", "ok", "handelExport", "handelSearch"]);

const tableParams = ref({
  page: 1,
  size: 10
});

const handelExport = () => {
  emit("handelExport");
};
const visibleDel = ref(false);
const modelVisible = computed({
  get: () => {
    return props.visible;
  },
  set: val => {
    emit("update:visible", val);
  }
});
const percentage = ref(0);
const uploading = ref(false);
const tableList = ref([]);
const closeUpload = ref(false);
const recordTotal = ref(0);
const errorMsg = ref("");
const customRequest = async options => {
  uploading.value = true;
  closeUpload.value = false;
  const file = await upload(options, undefined, async percent => {
    percentage.value = (percent * 100).toFixed(2);
  });
  if (!closeUpload.value) {
    const formData = new FormData();
    formData.append("file", options.file);
    try {
      await managementImport(file.url, formData);
      status.value = "success";
    } catch (error) {
      errorMsg.value = error.message.replace(/,/g, "; ");
      status.value = "error";
    }
  }
};
const status = ref("loading");
const statusList = {
  loading: { title: "正在导入...", tip: "正在请求权限，大约剩余5s", btnText: "取消上传" },
  success: {
    title: "导入成功",
    tip: "导入成功",
    btnText: "我知道了"
  },
  error: {
    title: "出错了",
    tip: "失败原因。您导入的数据模板中，存在必填项数据缺失，根据提示内容，请补充完整后重新导入",
    btnText: "我知道了"
  }
};
const getList = async () => {
  const res = await logsList(tableParams.value);
  tableList.value = [...tableList.value, ...res.data.list];
  recordTotal.value = res.data.total;
};
const scroll = ({ scrollTop }) => {
  const { scrollHeight, clientHeight } = scrollRef.value.wrapRef;
  if (scrollTop + clientHeight >= scrollHeight) {
    if (
      recordTotal.value > tableParams.value.size &&
      Math.ceil(recordTotal.value / tableParams.value.size) > tableParams.value.page
    ) {
      tableParams.value.page += 1;
      getList();
    }
  }
};
const next = () => {
  switch (status.value) {
    case "loading":
      closeUpload.value = true;
      uploading.value = false;
      status.value = "loading";
      break;
    case "error":
      uploading.value = false;
      status.value = "loading";
      break;
    case "success":
      emit("ok");
      modelVisible.value = false;
      uploading.value = false;
      status.value = "loading";
      emit("handelSearch");
      break;
    default:
      break;
  }
};
const delId = ref("");
// 点击删除
const openDel = id => {
  delId.value = id;
  visibleDel.value = true;
};
// 删除
const handleDel = async () => {
  visibleDel.value = false;
  await deleteLogs(delId.value);
  ElMessage.success("删除成功");
  tableParams.value.page = 1;
  tableList.value = [];
  await getList();
};
const downFile = (url, name) => {
  const a = document.createElement("a");
  a.href = url;
  a.download = name;
  a.click();
  window.open(url);
};
const change = key => {
  switch (key) {
    case 1:
      break;
    case 2:
      tableList.value = [];
      getList();
      break;
  }
};
</script>

<style lang="scss" scoped>
$topic: #007dff;

.tabs-container {
  ::v-deep(.el-tabs__nav-wrap::after) {
    height: 1px;
  }

  ::v-deep(.el-tabs__item.is-active) {
    color: $topic;
  }

  ::v-deep(.el-tabs__active-bar) {
    background: $topic;
  }

  ::v-deep(.el-tabs__item:hover) {
    color: $topic;
  }
}

.hint {
  height: 54px;
  background: #e3f0fe;
  border-radius: 6px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;

  div {
    display: flex;
    align-items: center;
    gap: 10px;

    ::v-deep(.el-icon) {
      color: #0052d9;
    }
  }

  span {
    font-size: 14px;
    color: rgba(0, 0, 0, 0.6);
    cursor: pointer;
  }
}

.upload-demo {
  margin-top: 20px;

  img {
    height: 80px;
    width: 80px;
  }

  em {
    color: $topic;
  }

  .tip {
    color: #86909c;
    font-size: 12px;
    margin-top: 10px;
  }

  .el-upload__tip {
    cursor: pointer;
    width: 200px;
    color: $topic;
    font-size: 16px;
    display: flex;
    align-content: center;
    gap: 8px;
    margin-top: 10px;
    user-select: none;

    .el-icon {
      font-size: 18px;
    }
  }
}

.uploading {
  background: #ffffff;
  border-radius: 10px;
  border: 1px dashed #c0c4cc;
  margin-top: 20px;
  padding-top: 40px;
  padding-bottom: 20px;
  box-sizing: border-box;

  > div {
    display: flex;
    justify-content: center;
  }

  .el-icon {
    font-size: 126px;
    color: var(--color);
  }

  .status {
    margin-top: 10px;
  }

  .tip {
    color: #86909c;
    font-size: 12px;
    margin: 10px auto;
  }

  .success-tip {
    display: block;
    background: #f5f7fa;
    border-radius: 4px;
    color: #4e5969;
    margin: 10px 10px 0;
    padding: 10px;
    font-size: 12px;
    line-height: 26px;
    white-space: pre-wrap;
    /* 或者 pre-line */
    word-wrap: break-word;
  }
}

.dialog-footer {
  .el-button--primary {
    background: $topic;
    border-radius: 0;
    border: none;
  }

  .el-button {
    border-radius: 0;
  }
}

.table {
  $border: 1px solid #dcdfe6;
  margin-top: 20px;

  .row {
    display: grid;
    grid-template-columns: 1fr 2fr repeat(2, 1fr);
    border-bottom: $border;

    > div {
      height: 40px;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    img {
      width: 20px;
      height: 20px;
    }

    .operate {
      display: flex;
      gap: 20px;
    }
  }

  > .row:first-child {
    background: #f2f6fc;
    border: none;
  }

  .row:last-child {
    border-bottom: none;
  }
}

.sure {
  text-align: center;

  ::v-deep(.el-icon) {
    font-size: 60px;
    margin-bottom: 20px;
    color: rgb(255, 51, 51);
  }
}
</style>
